package com.chi.config;

import com.chi.pojo.User;
import com.chi.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component(value = "userRealm")
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //授权---每次访问config中有权限的资源，都会进行授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进行了授权！！");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addObjectPermission();
        //拿到当前用户的登录对象
        User user = (User) principalCollection.getPrimaryPrincipal();
        info.addStringPermission(user.getPerms());
        return info;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("进行了认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userService.queryUserByName(token.getUsername());
        if (user == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),"");
        //必须把user传进去，否则上面的principalCollection取不到user对象

        return info;
    }
}
